//
//  BaseTabBarView.swift
//  dysaidao
//
//  Created by Penlon Kim on 2022/3/2.
//  Copyright © 2022 王锦发. All rights reserved.
//

import UIKit
import SnapKit

class BaseTabBarView: BaseView {
    
    /// 当前选中的item
    var selectedIndex = 0 {
        didSet {
            for case let button as BKLayoutButton in stackView.arrangedSubviews {
                button.isSelected = (button.tag == selectedIndex)
                if button.isSelected {
                    button.bk_scaleAnimate()
                }
            }
        }
    }
    
    init(items: [[TabBarKeys: String]]) {
        super.init(frame: .zero)
        
        self.backgroundColor = ColorDef.dark27
        self.addSubview(stackView)
        stackView.snp.makeConstraints { make in
            make.left.right.equalToSuperview()
            make.top.equalTo(isFullScreen ? 8 : 3)
            make.height.equalTo(kTabBarHeight-kBottomSafeHeight)
        }
        
        self.preReload(by: items)
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    // MARK: - lazy
    private lazy var stackView: UIStackView = {
        let _stackView = UIStackView()
        _stackView.backgroundColor = .clear
        _stackView.axis = .horizontal
        _stackView.spacing = 1
        _stackView.alignment = .fill
        _stackView.distribution = .fillEqually
        return _stackView
    }()
    
}

// MARK: - Private
extension BaseTabBarView {
    
    private func preReload(by items: [[TabBarKeys: String]]) {
        stackView.removeAllSubviews()
        items.enumerated().forEach { (i, item) in
            let btn = self.createItem(by: item, with: i)
            stackView.addArrangedSubview(btn)
        }
    }
    
    private func createItem(by item: [TabBarKeys: String], with index: Int) -> BKLayoutButton {
        let btn = BKLayoutButton()
        btn.isUserInteractionEnabled = false
        btn.layoutStyle = .upImageDownTitle
        btn.setMidSpacing(7.5)
        btn.tag = index
        btn.titleLabel?.font = .systemFont(ofSize: isFullScreen ? 12 : 11)
        btn.setTitleColor(ColorDef.gray153, for: .normal)
        btn.setTitleColor(.white, for: .selected)
        btn.setTitle(item[.kTabBarTitle], for: .normal)
        btn.isSelected = (selectedIndex == index)
        btn.setImage(UIImage(named: item[.kTabBarImage]!), for: .normal)
        btn.setImage(UIImage(named: item[.kTabBarImageSelect]!), for: .selected)
        btn.setImageSize(CGSizeMake(18, 18))
        return btn
    }
    
}
